import threading
from app.config import MAKE_SCREENSHOTS
from app.request import Requests

from core.models import Link

colors = {
    'gray'    : 30,
    'red'     : 31,
    'green'   : 32,
    'yellow'  : 33,
    'blue'    : 34,
    'magenta' : 35,
    'cyan'    : 36,
    'white'   : 37,
    'crimson' : 38,
    'hred'    : 41,
    'hgreen'  : 42,
    'hbrown'  : 43,
    'hblue'   : 44,
    'hmagenta': 45,
    'hcyan'   : 46,
    'hgray'   : 47,
    'hcrimson': 48,
}

# For now it is used just to print out some message strings
# TODO: add logging options to informator
def informator(logstr = '', color = 'red'):
    print '\033[1;%dm%s\033[1;m' % (colors.get(color), logstr)

def link_info(link = Link):
    informator('URI: %s\t' % link.link)

    if link.screenshot:
        informator('\tTake screenshot: Yes')
    else:
        informator('\tTake screenshot: No')

    if link.dump:
        informator('\tMake page dump: Yes\n')
    else:
        informator('\tMake page dump: No\n')

class Elements:
    # Split array into equal chunks and return these chunk blocks
    def __init__(self):
        pass

    def split_equal(self, num_threads = 1, array = None):
        if not array:
            return

        chunk_size = len(array) / num_threads + len(array) % num_threads

        for item in xrange(0, len(array), chunk_size):
            yield array[item: item + chunk_size]

class Worker:
    def __init__(self, proxy_info = object, schedule = None, provider = None):
        # request_maker is able to make request via proxy and direct request
        # >>> request_maker.direct()
        # >>> request_maker.proxy()

        self.proxy = proxy_info
        self.schedule = schedule
        self.provider = provider
        self.simple_request = Requests(proxy_info = self.proxy)

    def start(self, links = None, scan = None, schedule = None):
        for link in links:
            link_info(link = link)
            
            request = self.simple_request

            request.set_uri(link = link)
            request.perform(scan = scan, schedule = schedule)

class ThreadWorker(threading.Thread):
    def __init__(self, worker=object, scan=None, links=None, schedule=None):
        self.scan = scan
        self.links = links
        self.schedule = schedule
        self.worker = worker
        threading.Thread.__init__(self)

    def run(self):
        self.worker.start(links=self.links, scan=self.scan, schedule=self.schedule)
        
